﻿using System.Net;
using System.Windows;
using log4net;
using TwitterLib;
using System.Windows.Input;
using TweetSharp.Model;

namespace Pawing
{
	public partial class LoginControl
    {
		public static RoutedCommand RequestPin = new RoutedCommand();
		public static RoutedCommand SupplyPin = new RoutedCommand();
        public TwitterNet Twitter { get; set; }
        private static readonly ILog logger = LogManager.GetLogger("Pawing.Logging");
        private readonly Properties.Settings AppSettings = Properties.Settings.Default;
		public string Pin { get; set; }
		private delegate void LoginDelegate(TwitterNet arg);
        private delegate void PostLoginDelegate(OAuthToken arg);

        public LoginControl()
        {
            this.InitializeComponent();
        }

        private void SupplyPin_Executed(object sender, RoutedEventArgs e)
        {
            // Attempt login in a new thread
            LoginButton.Dispatcher.BeginInvoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                new LoginDelegate(TryLogin), Twitter);
        }

        private void TryLogin(TwitterNet twitter)
        {
            try
            {
                // Schedule the update function in the UI thread.
                LayoutRoot.Dispatcher.BeginInvoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new PostLoginDelegate(UpdatePostLoginInterface), 
                    twitter.Authenticate(pinEdit.Text.Trim()));
            }
            catch (WebException ex)
            {
                logger.Error("登陆微博过程中发生错误");
                MessageBox.Show("登陆微博过程中发生错误。" + ex.Message);
            }
            catch (RateLimitException ex)
            {
                logger.Error("接口请求次数超过限制");
                MessageBox.Show(ex.Message);
            }
            catch (ProxyAuthenticationRequiredException ex)
            {
                logger.Error("不正确的代理服务器配置");
                MessageBox.Show("代理服务器没有正确配置，请修改设置菜单中的代理服务器设置");
            }
        }

        private void UpdatePostLoginInterface(OAuthToken token)
        {
            if (token != null)
            {
                App.LoggedInUser = Twitter.Login(token);
                if (App.LoggedInUser != null)
                {
                    AppSettings.Username = App.LoggedInUser.ScreenName;
                    AppSettings.UserId = App.LoggedInUser.Id;
                    AppSettings.OAuthToken = token.Token;
                    AppSettings.OAuthTokenSecret = token.TokenSecret;
                    AppSettings.LastUpdated = string.Empty;

                    AppSettings.Save();

                    RaiseEvent(new RoutedEventArgs(LoginEvent));
                }
                else
                {
                    MessageBox.Show("不正确的用户名和密码，请尝试重新登陆。");
                }
            }
        }

        public static readonly RoutedEvent LoginEvent =
            EventManager.RegisterRoutedEvent("Login", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(LoginControl));

        public event RoutedEventHandler Login
        {
            add { AddHandler(LoginEvent, value); }
            remove { RemoveHandler(LoginEvent, value); }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            // Set Username textbox as default focus
            LoginButton.Focus();
        }

		private void RequestPin_Executed(object sender, ExecutedRoutedEventArgs e) {
			Twitter.FetchPin(AppSettings.ConsumerKey, AppSettings.ConsumerSecret);
		}
    }
}
